package com.xyazm.order.service.impl;

import com.xyazm.common.enums.AmountTypeEnum;
import com.xyazm.common.enums.OrderStatusChangeEnum;
import com.xyazm.fulfill.domain.param.TriggerFulFillItemParam;
import com.xyazm.fulfill.domain.param.TriggerFulFillParam;
import com.xyazm.order.dao.OrderAmountDAO;
import com.xyazm.order.dao.OrderDeliveryDetailDAO;
import com.xyazm.order.dao.OrderItemDAO;
import com.xyazm.order.domain.dto.AfterFulfillDTO;
import com.xyazm.order.domain.entity.OrderAmountDO;
import com.xyazm.order.domain.entity.OrderDeliveryDetailDO;
import com.xyazm.order.domain.entity.OrderInfoDO;
import com.xyazm.order.domain.entity.OrderItemDO;
import com.xyazm.order.service.IOrderFulFillService;
import com.xyazm.order.statemachine.OrderStateMachine;
import com.xyazm.order.statemachine.StateMachineFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderFulFillService implements IOrderFulFillService {

    @Autowired
    private OrderItemDAO orderItemDAO;
    @Autowired
    private OrderAmountDAO orderAmountDAO;
    @Autowired
    private OrderDeliveryDetailDAO orderDeliveryDetailDAO;

    @Resource
    private StateMachineFactory stateMachineFactory;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void triggerOrderFulFill(String orderId) {
        // 状态机流转 -> 订单已履约
        OrderStatusChangeEnum event = OrderStatusChangeEnum.ORDER_FULFILLED;
        OrderStateMachine orderStateMachine = stateMachineFactory.getOrderStateMachine(event.getFromStatus());
        AfterFulfillDTO afterFulfillDTO = new AfterFulfillDTO();
        afterFulfillDTO.setOrderId(orderId);
        afterFulfillDTO.setStatusChange(event);
        orderStateMachine.fire(event, afterFulfillDTO);
    }

    @Override
    public void informOrderAfterFulfillResult(AfterFulfillDTO afterFulfillDTO) {
        // 状态机流转
        OrderStatusChangeEnum event = afterFulfillDTO.getStatusChange();
        OrderStateMachine orderStateMachine = stateMachineFactory.getOrderStateMachine(event.getFromStatus());
        orderStateMachine.fire(event, afterFulfillDTO);
    }


    /**
     * 构建订单履约入参
     * @author xuyou
     * @date: 2022/6/23 17:39
     * @param: orderInfo
     */
    @Override
    public TriggerFulFillParam buildTriggerFulFillParam(OrderInfoDO orderInfoDO) {
        OrderDeliveryDetailDO orderDeliveryDetailDO = orderDeliveryDetailDAO.getByOrderId(orderInfoDO.getOrderId());
        List<OrderItemDO> orderItemDOList = orderItemDAO.listByOrderId(orderInfoDO.getOrderId());

        //构造请求
        TriggerFulFillParam param = TriggerFulFillParam.builder()
                .businessIdentifier(orderInfoDO.getBusinessIdentifier())
                .orderId(orderInfoDO.getOrderId())
                .orderType(orderInfoDO.getOrderType())
                .sellerId(orderInfoDO.getSellerId())
                .userId(orderInfoDO.getUserId())
                .payType(orderInfoDO.getPayType())
                .payAmount(orderInfoDO.getPayAmount())
                .totalAmount(orderInfoDO.getTotalAmount())

                .deliveryType(orderDeliveryDetailDO.getDeliveryType())
                .receiverName(orderDeliveryDetailDO.getReceiverName())
                .receiverPhone(orderDeliveryDetailDO.getReceiverPhone())
                .receiverProvince(orderDeliveryDetailDO.getProvince())
                .receiverCity(orderDeliveryDetailDO.getCity())
                .receiverArea(orderDeliveryDetailDO.getArea())
                .receiverStreet(orderDeliveryDetailDO.getStreet())
                .receiverDetailAddress(orderDeliveryDetailDO.getDetailAddress())
                .receiverLat(orderDeliveryDetailDO.getLat())
                .receiverLon(orderDeliveryDetailDO.getLon())
                .triggerFulFillItems(buildTriggerFulFillItems(orderItemDOList))
                .build();
        // 查询运费价格
        OrderAmountDO deliveryAmount = orderAmountDAO.getOne(orderInfoDO.getOrderId(),
                AmountTypeEnum.SHIPPING_AMOUNT.getCode());
        if(deliveryAmount != null) {
            param.setDeliveryAmount(deliveryAmount.getAmount());
        }
        return param;
    }

    /**
     * 构建履约订单商品明细
     * @author xuyou
     * @date: 2022/6/23 18:16
     */
    private List<TriggerFulFillItemParam> buildTriggerFulFillItems(List<OrderItemDO> orderItemDOList) {
        return orderItemDOList.stream().map(item -> TriggerFulFillItemParam.builder()
               .skuCode(item.getSkuCode())
               .productType(item.getProductType())
               .productName(item.getProductName())
               .salePrice(item.getSalePrice())
               .saleQuantity(item.getSaleQuantity())
               .productUnit(item.getProductUnit())
               .payAmount(item.getPayAmount())
               .originAmount(item.getOriginAmount())
               .extJson(item.getExtJson())
               .build()).collect(Collectors.toList());
    }


}
